package com.zwh.producer;


import com.alibaba.fastjson.JSON;
import com.zwh.MsgModel;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Component
/**
 * 判断是否需要加载这个bean ，system.init_rocketmq是yml文件的配置信息，如果和havingValue中的值一样就可以加载
 * 如果该属性不存在，则根据matchIfMissing属性的设置决定是否生效，如果matchIfMissing为true，则在属性缺失时也会生效
 */
@ConditionalOnProperty(name = "system.init_rocketmq",havingValue = "true")
public class TestProducer {

    public String TOPIC = "testTopic";
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    public void test(){
        String msg = "测试发送的消息";

        //同步
        rocketMQTemplate.syncSend(TOPIC,msg);
        //异步
        rocketMQTemplate.asyncSend(TOPIC, msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("失败"+throwable.getMessage());
            }
        });

        //单向
        rocketMQTemplate.sendOneWay(TOPIC,msg);
        //延迟
        Message<String> build = MessageBuilder.withPayload("一个延迟消息").build();
        rocketMQTemplate.syncSend(TOPIC,build,3000,3);

        //顺序消息
        List<MsgModel> msgModels = Arrays.asList(
                new MsgModel("qwer","1","下单"),
                new MsgModel("qwer","1","短信"),
                new MsgModel("qwer","1","物流"),
                new MsgModel("asd","2","下单"),
                new MsgModel("asd","2","短信"),
                new MsgModel("asd","2","物流")
        );
        msgModels.forEach(x->{
            //发送一般是以json格式
            rocketMQTemplate.syncSendOrderly(TOPIC, JSON.toJSON(x),x.getOrderSn());
        });


    }
}
